﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using Shohdi.DataHandler;

public partial class GroupsEditEN : System.Web.UI.Page
{

    public List<GroupRules> lstCurrentGroupRules = new List<GroupRules>();


    public List<Groups> lstGroupsGrid
    {
        get
        {
            if (ViewState["lstGroupsGrid"] == null)
            {
                ViewState["lstGroupsGrid"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstGroupsGrid"].ToString()] == null)
            {
                Session[ViewState["lstGroupsGrid"].ToString()] = new List<Groups>();

            }

            return (List<Groups>)Session[ViewState["lstGroupsGrid"].ToString()];

        }
        set
        {
            if (ViewState["lstGroupsGrid"] == null)
            {
                ViewState["lstGroupsGrid"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstGroupsGrid"].ToString()] = value;
        }



    }




    long mGroupsID
    {
        get
        {
            if (ViewState["mGroupsID"] == null)
            {
                ViewState["mGroupsID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mGroupsID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["mGroupsID"].ToString()] = obj;

            }

            return (long)Session[ViewState["mGroupsID"].ToString()];

        }
        set
        {
            if (ViewState["mGroupsID"] == null)
            {
                ViewState["mGroupsID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mGroupsID"].ToString()] = value;
        }
    }


    Groups mObjGroups
    {
        get
        {
            if (ViewState["mObjGroups"] == null)
            {
                ViewState["mObjGroups"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mObjGroups"].ToString()] == null)
            {
                Session[ViewState["mObjGroups"].ToString()] = new Groups();

            }

            return (Groups)Session[ViewState["mObjGroups"].ToString()];

        }
        set
        {
            if (ViewState["mObjGroups"] == null)
            {
                ViewState["mObjGroups"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mObjGroups"].ToString()] = value;
        }
    }






    protected void Page_Load(object sender, EventArgs e)
    {



        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);

        if (!Page.IsPostBack)
        {
            bindGroupRules();

            bindGrid("");
            editLoad();
        }



    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {

        List<Groups> lstGroups = search(strIn);



        lstGroupsGrid = lstGroups;

        grdUsers.DataSource = lstGroups;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Groups_page))
            Response.Redirect("LoginEN.aspx");


        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_groups_page))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }





    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);

    }

    /// <summary>
    /// this function will search in Groups and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of Groups objects matched</returns>
    protected List<Groups> search(string txtText)
    {
        GroupsDB objGroupsDB = new GroupsDB(ConnectionStrings.LMS);
        List<Groups> lstRet = new List<Groups>();
        if (txtText.Trim() == "")
        {
            List<Groups> lstNew = objGroupsDB.Select(" top 100 ", " where [SystemGroup] <> '1' order by [GroupNameEN] ");
            //lstNew = new List<Groups>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            //no status
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            Groups objGroups = new Groups();

            string compareValue = "'%" + strValue.Replace("'", "''") + "%'";


            string strWhere = " where ";
            strWhere += " ([GroupNameAR] LIKE " + compareValue + " OR [GroupNameEN] LIKE " + compareValue + " ) AND [SystemGroup] <> '1' ";



            List<Groups> lstGroups = objGroupsDB.Select(" top 100 ", strWhere);
            //lstGroups = new List<Groups>(from objFol in lstGroups where objFol.StatusID != 2 select objFol);
            //no status
            foreach (Groups objFol in lstGroups)
            {
                //if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).ToList().Count == 0)
                if (!lstRet.Contains(objFol))
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_groups_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long GroupsID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        GroupsDB objGroupsDB = new GroupsDB(ConnectionStrings.LMS);
        List<Groups> lstGroups = objGroupsDB.getGroupsByID(GroupsID);




        if (lstGroups.Count == 0)
        {
            lblError.Text = "No groups to delete";
            lblResult.Text = "";
            return;
        }




        ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);


        List<PersonGroups> lstPersonGroups = lstGroups[0].lstPersonGroups;
        List<GroupRules> lstGroupRules = lstGroups[0].lstGroupRules;

        con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);



        try
        {
            foreach (PersonGroups obj in lstPersonGroups)
            {
                PersonGroupsDB pdb = new PersonGroupsDB();
                pdb.Delete(con, obj);
            }

            foreach (GroupRules obj in lstGroupRules)
            {
                GroupRulesDB grd = new GroupRulesDB();
                grd.Delete(con, obj);
            }


            objGroupsDB.Delete(con, lstGroups[0]);

            con.CommitTransConnection();


            lblResult.Text = "Deleted ok.";
            bindGrid(txtSearch.Text);

        }

        catch
        {

            con.RollbackTransConnection();

            lblError.Text = "Error deleting group, try again later !";


        }















    }


    protected void btnNew_Click(object sender, EventArgs e)
    {
        clearAllControls();
    }


    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstGroupsGrid;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind();
    }


    /// <summary>
    /// this function will check mGroupsID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        if (mGroupsID != -1)
        {
            try
            {

                GroupsDB objGroupsDB = new GroupsDB(ConnectionStrings.LMS);
                string strWhere = " where  [ID]='" + mGroupsID.ToString() + "' AND [SystemGroup] <> '1' ";

                List<Groups> lstGroups = objGroupsDB.Select("", strWhere);
                if (lstGroups.Count > 0)
                {


                    mObjGroups = lstGroups[0];
                    btnDelete.Visible = true;

                }
                else
                {
                    mGroupsID = -1;
                    mObjGroups = new Groups();
                    mGroupsID = ((long)-1);

                }


            }
            catch
            {
                mGroupsID = ((long)-1);
            }



        }
        else
        {

            btnDelete.Visible = false;

        }
    }



    /// <summary>
    /// this will bind the group data to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        if (mGroupsID != -1)
        {

            txtGroupNameAR.Text = mObjGroups.GroupNameAR;
            txtGroupNameEN.Text = mObjGroups.GroupNameEN;

            if (chkGroupRules.Items.Count == 0)
                bindGroupRules();


            for (int i = 0; i < chkGroupRules.Items.Count; i++)
            {
                chkGroupRules.Items[i].Selected = false;
            }

            foreach (GroupRules obj in mObjGroups.lstGroupRules)
            {
                for (int i = 0; i < chkGroupRules.Items.Count; i++)
                {
                    long val = long.Parse(chkGroupRules.Items[i].Value);

                    if (val == obj.RuleID)
                    {
                        chkGroupRules.Items[i].Selected = true;
                    }

                }
            }



        }
    }



    /// <summary>
    /// this function will bind a list of checkboxes with rules
    /// </summary>
    private void bindGroupRules()
    {
        RulesDB objRulesDB = new RulesDB(ConnectionStrings.LMS);
        List<Rules> lstRules = objRulesDB.Search(new Rules());

        chkGroupRules.DataSource = lstRules;
        chkGroupRules.DataTextField = "RuleDescriptionEN";
        chkGroupRules.DataValueField = "ID";
        chkGroupRules.DataBind();

    }



    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {

        mObjGroups.GroupNameAR = txtGroupNameAR.Text;
        mObjGroups.GroupNameEN = txtGroupNameEN.Text;

        mObjGroups.SystemGroup = false;

        lstCurrentGroupRules.Clear();

        for (int i = 0; i < chkGroupRules.Items.Count; i++)
        {
            if (chkGroupRules.Items[i].Selected)
            {
                GroupRules obj = new GroupRules();
                obj.RuleID = long.Parse(chkGroupRules.Items[i].Value);
                lstCurrentGroupRules.Add(obj);

            }

        }


    }



    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {

        txtGroupNameAR.Text = "";
        txtGroupNameEN.Text = "";



        for (int i = 0; i < chkGroupRules.Items.Count; i++)
        {
            chkGroupRules.Items[i].Selected = false;


        }

        mObjGroups = new Groups();

        mGroupsID = -1;

    }



    /// <summary>
    /// this function for loading the editing behavior
    /// </summary>
    protected void editLoad()
    {


        Persons currentPerson = GlobalVars.getCurrentPerson();






        checkSecurityAndCustomizePage(currentPerson);

        checkID();


        BindAllControls();





    }



    /// <summary>
    /// this function will Save the data
    /// </summary>
    protected void Save()
    {


        if (checkForRepeats())
        {
            GroupsDB objGroupsDB = new GroupsDB(ConnectionStrings.LMS);
            GroupRulesDB objGroupRulesDB = new GroupRulesDB(ConnectionStrings.LMS);
            List<GroupRules> lstOld = mObjGroups.lstGroupRules;
            
            if (mObjGroups.ID == -1)
            {


                ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);
                con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);


                try
                {
                    foreach (GroupRules obj in lstOld)
                    {
                        objGroupRulesDB.Delete(con, obj);
                    }

                    objGroupsDB.Insert(con, mObjGroups);

                    foreach (GroupRules obj in lstCurrentGroupRules)
                    {
                        obj.GroupID = mObjGroups.ID;
                        objGroupRulesDB.Insert(con, obj);
                    }


                    con.CommitTransConnection();
                    clearAllControls();
                    bindGrid(txtSearch.Text);
                    lblResult.Text = "Data saved ok.";


                }
                catch
                {
                    con.RollbackTransConnection();
                    lblError.Text = "Error saving , try again later";



                }






                
               
            }
            else
            {

                ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);
                con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);

                try
                {
                    foreach (GroupRules obj in lstOld)
                    {
                        objGroupRulesDB.Delete(con, obj);
                    }

                    
                    objGroupsDB.Update(con , mObjGroups);



                    foreach (GroupRules obj in lstCurrentGroupRules)
                    {
                        obj.GroupID = mObjGroups.ID;
                        objGroupRulesDB.Insert(con, obj);
                    }



                    con.CommitTransConnection();

                    bindGrid(txtSearch.Text);
                    BindAllControls();
                    lblResult.Text = "Group saved ok.";


                }
                catch
                {
                    con.RollbackTransConnection();

                    lblError.Text = "Error saving , try again later";


                }







                
                

            }



        }


    }


    /// <summary>
    /// this function will check if the data exist with the same Name or not
    /// </summary>
    /// <returns>true if ok , false for error (data  exist before)</returns>
    protected bool checkForRepeats()
    {

       
        GroupsDB objGroupsDB = new GroupsDB(ConnectionStrings.LMS);

        string strGroupNameAR = "'" + mObjGroups.GroupNameAR.Replace("'", "''") + "'";
        string strGroupNameEN = "'" + mObjGroups.GroupNameEN.Replace("'", "''") + "'";


        string strWhere = " where ([GroupNameAR] = " + strGroupNameAR + " OR [GroupNameEN] = " + strGroupNameEN + ") AND [ID] <> '" + mObjGroups.ID + "' ";


        List<Groups> lstExist = objGroupsDB.Select("", strWhere);

        

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }


       





        return true;

    }




    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {

        lblError.Text = "Error , the group  is already found !";

    }



    protected void btnSave_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_groups_page))
            return;


        if (Page.IsValid)
        {



            ReadAllControls();






            Save();


        }
    }




    protected void btnDelete_Click(object sender, EventArgs e)
    {



                Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_groups_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long GroupsID = mObjGroups.ID;



        GroupsDB objGroupsDB = new GroupsDB(ConnectionStrings.LMS);
        List<Groups> lstGroups = objGroupsDB.getGroupsByID(GroupsID);




        if (lstGroups.Count == 0)
        {
            lblError.Text = "No groups to delete";
            lblResult.Text = "";
            return;
        }




        ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);


        List<PersonGroups> lstPersonGroups = lstGroups[0].lstPersonGroups;
        List<GroupRules> lstGroupRules = lstGroups[0].lstGroupRules;

        con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);



        try
        {
            foreach (PersonGroups obj in lstPersonGroups)
            {
                PersonGroupsDB pdb = new PersonGroupsDB();
                pdb.Delete(con, obj);
            }

            foreach (GroupRules obj in lstGroupRules)
            {
                GroupRulesDB grd = new GroupRulesDB();
                grd.Delete(con, obj);
            }


            objGroupsDB.Delete(con, lstGroups[0]);

            con.CommitTransConnection();


            lblResult.Text = "Deleted ok.";
            clearAllControls();

            bindGrid(txtSearch.Text);

        }

        catch
        {

            con.RollbackTransConnection();

            lblError.Text = "Error deleting group, try again later !";





        }






    }




    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);



        long GroupsID = long.Parse(grdUsers.DataKeys[e.NewEditIndex]["ID"].ToString());

        mGroupsID = GroupsID;

        editLoad();

        e.Cancel = true;

    }
}
